<template>
  <view class="user-info">
    <!-- 用户信息展示 -->
    <view class="user-info-container">
      <image class="user-avatar" :src="getImg + userInfo.avatar" mode="aspectFill"></image>
      <text class="user-nickname">{{ userInfo.nickname }}</text>
    </view>

    <!-- 表单组件 -->
    <form ref="form" @submit="onSubmit">
      <view class="form-container">
        <!-- 选择房屋 -->
        <view class="field-container">
          <text class="label">选择房屋</text>
          <input class="input" disabled :value="name" placeholder="请选择房产" @click="goLink" />
        </view>

        <!-- 姓名 -->
        <view class="field-container">
          <text class="label">姓名</text>
          <input class="input" v-model="formData.ebUserName" placeholder="姓名" required />
        </view>

        <!-- 联系电话 -->
        <view class="field-container">
          <text class="label">联系电话</text>
          <input class="input" maxlength="11" v-model="formData.contactPhone" placeholder="联系电话" required />
        </view>

        <!-- 级联选择器-->
        <view v-if="name" class="field-container">
          <text class="label">楼栋号</text>
          <input class="input" v-model="formData.ebComunityLdName" disabled @click="showBuildingPicker"
            placeholder="请选择楼栋号" />
        </view>

        <view v-if="formData.ebComunityLdName" class="field-container">
          <text class="label">单元号</text>
          <input class="input" v-model="formData.ebComunityDyName" disabled @click="showUnitPicker"
            placeholder="请选择单元号" />
        </view>

        <!-- <view v-if="formData.ebComunityDyName" class="field-container">
        <text class="label">楼层号</text>
        <input class="input" v-model="formData.ebComunityLayerName" disabled @click="showFloorPicker" placeholder="请选择楼层号" />
      </view> -->

        <view v-if="formData.ebComunityDyName" class="field-container" style="position: relative;">
          <text class="label">房间号</text>
          <input class="input" v-model="formData.houseNum" placeholder="请选择房间号" />
          <div class="dwdawwadf" style="" v-show="isMoom">
            <div v-for="(item, index) in initMoom" @click="dwadavdwad(item)" :key="index" @blur="isMoom = false"
              style="height: 30px; line-height: 30px; color: #000; border-bottom: 1px solid #ededed">{{ item.text }}
            </div>
          </div>
        </view>

        <view v-if="name" class="field-container">
          <text class="label">房屋面积</text>
          <input class="input" v-model="formData.houseArea" disabled placeholder="房屋面积" />
        </view>
        <view v-if="name" class="field-container">
          <text class="label">详细地址</text>
          <input class="input" v-model="formData.address" disabled placeholder="具体地址" />
        </view>

      </view>
    </form>
    <!-- 提交按钮 -->
    <view class="submit-container">
      <button class="submit-btn" :loading="loading" @click="onSubmit">确定</button>
    </view>
    <!-- 楼栋 -->
    <u-picker :show="showBuildingPopup" :columns="buildingColumns" @cancel="showBuildingPopup = false"
      @confirm="onBuildingConfirm" :loading="loading"></u-picker>
    <!-- 单元 -->
    <u-picker :show="showUnitPopup" :columns="unitColumns" @cancel="showUnitPopup = false" @confirm="onUnitConfirm"
      :loading="loading"></u-picker>
    <!-- 楼层 -->
    <u-picker :show="showFloorPopup" :columns="floorColumns" @cancel="showFloorPopup = false" @confirm="onFloorConfirm"
      :loading="loading"></u-picker>
    <!-- 房间号 -->
    <u-picker :show="showRoomPopup" :columns="roomColumns" @cancel="showRoomPopup = false" @confirm="onRoomConfirm"
      :loading="loading"></u-picker>
  </view>
</template>

<script>
import { propertyMyHouseById, bindHouse } from "../../../utils/api/local.js";
import { IMG_URL, checkPhone } from "../../../config/index.js";
export default {
  data() {
    return {
      userInfo:'',
      getImg: IMG_URL,
      checkPhone,
      // 表单数据（简化数据结构）
      formData: {
        ebComunityId: "", // 小区ID
        ebUserName: "", // 用户姓名
        contactPhone: "", // 联系电话
        ebComunityLdName: "", // 楼栋名称
        ebComunityDyName: "", // 单元名称
        ebComunityLayerName: "", // 楼层名称
        houseNum: "", // 房间号
        houseArea: "", // 房屋面积
        id: "", // 房间号ID
      },
      messages: {
        ebComunityId: "",
        ebComunityLdName: "",
        ebComunityDyName: "",
        ebComunityLayerName: "",
        houseNum: "",
        groupType: "comunity",
      },
      isMoom: false,
      showBuildingPopup: false,
      showUnitPopup: false,
      showFloorPopup: false,
      showRoomPopup: false,
      name: "",
      houseInfo: {},
      floors: [],
      rooms: [],

      // 级联数据
      units: [], // 单元列表
      floors: [], // 楼层列表
      rooms: [], // 房间列表
      // 选择器数据
      buildingColumns: [], // 楼栋选项
      unitColumns: [], // 单元选项
      floorColumns: [], // 楼层选项
      loading: false,
      roomColumns: [], // 房间选项
      initMoom: []
    };
  },
  watch: {
    'formData.houseNum': {
      handler(newVal, oldVal) {
        this.initMoom = []
        if (this.roomColumns.length > 0) {
          this.roomColumns[0].forEach((item) => {
            if (item.text.indexOf(newVal) != -1) {
              this.initMoom.push(item)
            }
          })
          // if(this.initMoom.length > 0) {
          this.isMoom = true
          // }
        }

      },
      deep: true
    }
  },
  onShow() {
    this.userInfo = uni.getStorageSync("userInfo");
    uni.$on("houseData", (data) => {
      this.getInfo(data);
    });
  },
  methods: {
    dwadavdwad(item) {
      this.formData.houseArea = item.houseArea
      this.formData.address = item.address
      this.formData.houseNum = item.text
      this.formData.id = item.value
      setTimeout(() => {
        this.isMoom = false
      }, 500)
    },
    // 获取房屋信息并加载楼栋数据
    getInfo(data) {
      // 重置选择状态
      this.isBuildingSelected = false;
      this.isUnitSelected = false;
      this.isFloorSelected = false;
      this.isRoomSelected = false;
      this.name = data.name;
      this.messages.ebComunityId = data.id;
      this.houseInfo = data;
      this.fetchBuildings(); // 获取楼栋信息
    },

    resetChildren(type) {
      const clearMap = {
        building: ["ebComunityLdName", "ebComunityDyName", "ebComunityLayerName", "houseNum"],
        unit: ["ebComunityDyName", "ebComunityLayerName", "houseNum"],
        floor: ["ebComunityLayerName", "houseNum"],
        room: ["houseNum"],
      };
      clearMap[type].forEach((key) => (this.formData[key] = ""));
    },

    // 获取楼栋数据（带参数校验）
    async fetchBuildings() {
      this.loading = true;
      try {
        const res = await propertyMyHouseById({
          ebComunityId: this.houseInfo.id,
          groupType: "comunity", // 明确请求类型
        });
        this.resetChildren("unit"); // 清除下级数据
        if (res.code === 200) {
          this.buildingColumns = [
            res.data
              .filter((building) => building.ebComunityLdName) // 过滤掉 ebComunityLdName 为空的项
              .map((building) => building.ebComunityLdName),
          ];
          this.loading = false;
          if (this.buildingColumns.length === 0) {
            // 检查数组是否为空
            uni.showToast({
              title: "暂无数据",
              icon: "none",
            });
          }
        }
      } catch (error) {
        this.loading = false;
        uni.showToast({
          title: "楼栋数据请求失败:" + error.message,
          icon: "none",
        });
      }
    },

    onBuildingConfirm(value) {
      this.formData.ebComunityLdName = value.value[0];
      this.showBuildingPopup = false;
      this.formData.ebComunityDyName = ""; // 清空单元号
      this.fetchUnits();
    },

    async fetchUnits() {
      this.loading = true;
      try {
        const res = await propertyMyHouseById({
          ebComunityId: this.houseInfo.id,
          ebComunityLdName: this.formData.ebComunityLdName,
          groupType: "ld",
        });
        this.resetChildren("floor");
        if (res.code === 200) {
          this.unitColumns = [
            res.data
              .filter((unit) => unit.ebComunityDyName) // 过滤掉 ebComunityLdName 为空的项
              .map((unit) => unit.ebComunityDyName),
          ];
          this.loading = false;
          if (!this.unitColumns) {
            uni.showToast({
              title: "暂无数据",
              icon: "none",
            });
          }
          this.isUnitSelected = true;
        }
      } catch (error) {
        this.loading = false;
        uni.showToast({
          title: "楼栋数据请求失败:" + error.message,
          icon: "none",
        });
      }
    },

    // 获取楼层信息
    async fetchFloors() {
      this.loading = true;
      try {
        const res = await propertyMyHouseById({
          ebComunityId: this.houseInfo.id,
          ebComunityLdName: this.formData.ebComunityLdName,
          ebComunityDyName: this.formData.ebComunityDyName,
          groupType: "dy",
        });
        this.resetChildren("room");
        if (res.code === 200) {
          this.floorColumns = [
            res.data
              .filter((floor) => floor.ebComunityLayerName) // 过滤掉 ebComunityLdName 为空的项
              .map((floor) => floor.ebComunityLayerName),
          ];
          this.loading = false;
          if (!this.floorColumns) {
            uni.showToast({
              title: "暂无数据",
              icon: "none",
            });
          }
          this.isFloorSelected = true;
        }
      } catch (error) {
        this.loading = false;
        uni.showToast({
          title: "数据请求失败:" + error.message,
          icon: "none",
        });
      }
    },

    // 获取房间号信息
    async fetchRooms() {
      this.loading = true;
      try {
        const res = await propertyMyHouseById({
          ebComunityId: this.houseInfo.id,
          ebComunityLdName: this.formData.ebComunityLdName,
          ebComunityDyName: this.formData.ebComunityDyName,
          ebComunityLayerName: this.formData.ebComunityLayerName,
          groupType: "dy",
        });
        if (res.code === 200) {
          this.roomColumns = [
            res.data
              .filter((room) => room.houseNum) // 过滤掉 ebComunityLdName 为空的项
              .map((room) => ({
                text: room.houseNum,
                value: room.id,
                houseArea: room.houseArea,
                address: room.address,
              })),
          ];
          // this.formData.houseNum = res.data[0].houseNum;
          // this.formData.houseId = res.data[0].id; // 存储房间号ID
          // this.formData.houseArea = res.data[0].houseArea;
          this.loading = false;
          this.isRoomSelected = true;
          this.loading = false;
        }
      } catch (error) {
        this.loading = false;
        uni.showToast({
          title: "数据请求失败:" + error.message,
          icon: "none",
        });
      }
    },

    onSubmit() {
      if (!this.name) {
        uni.showToast({
          title: "请选择房产",
          icon: "none",
        });
        return;
      }
      if (!this.formData.ebUserName) {
        uni.showToast({
          title: "请输入姓名",
          icon: "none",
        });
        return;
      }
      if (!this.formData.contactPhone) {
        uni.showToast({
          title: "请输入联系电话",
          icon: "none",
        });
        return;
      }
      if (!checkPhone(this.formData.contactPhone)) {
        uni.showToast({
          title: "请输入正确的联系电话",
          icon: "none",
        });
        return;
      }
      if (!this.formData.ebComunityLdName) {
        uni.showToast({
          title: "请选择楼栋号",
          icon: "none",
        });
        return;
      }
      if (!this.formData.ebComunityDyName) {
        uni.showToast({
          title: "请选择单元号",
          icon: "none",
        });
        return;
      }
      // if (!this.formData.ebComunityLayerName) {
      //   uni.showToast({
      //     title: "请选择楼层号",
      //     icon: "none",
      //   });
      //   return;
      // }
      if (!this.formData.houseNum) {
        uni.showToast({
          title: "请选择房间号",
          icon: "none",
        });
        return;
      }
      if (!this.formData.houseArea) {
        uni.showToast({
          title: "房屋面积为空，请联系物业处理",
          icon: "none",
        });
        return;
      }
      this.loading = true;
      bindHouse({
        id: this.formData.id,
        ebUserId: uni.getStorageSync("uid"),
      })
        .then((res) => {
          uni.showToast({
            title: res.message,
            icon: "none",
          });
          this.loading = false;
          if (res.code === 200) {
            uni.navigateBack({
              delta: 1,
            });
          }
        })
        .catch((res) => {
          uni.showToast({
            title: res,
            icon: "none",
          });
          this.loading = false;
        });
    },
    togglePicker(type, show) {
      this[`show${type}Popup`] = show;
    },
    goLink() {
      uni.navigateTo({
        url: "/pages_h5/wy/index_list/list_house",
      });
      this.resetChildren("building");
    },
    showBuildingPicker() {
      this.showBuildingPopup = true;
    },
    onBuildingCancel() {
      this.showBuildingPopup = false;
    },
    showUnitPicker() {
      this.showUnitPopup = true;
    },
    onUnitConfirm(value) {
      this.formData.ebComunityDyName = value.value[0];
      this.formData.houseNum = ""; // 清空楼层号
      this.initMoom = []
      this.isMoom = false
      this.showUnitPopup = false;
      this.fetchRooms();
    },
    onUnitCancel() {
      this.showUnitPopup = false;
    },
    showFloorPicker() {
      this.showFloorPopup = true;
    },
    onFloorConfirm(value) {
      this.formData.ebComunityLayerName = value.value[0];
      this.formData.houseNum = ""; // 清空房间号
      this.showFloorPopup = false;
      this.fetchRooms();
    },
    onFloorCancel() {
      this.showFloorPopup = false;
    },
    showRoomPicker() {
      this.showRoomPopup = true;
    },
    onRoomConfirm(value) {
      this.formData.houseNum = value.value[0].text;
      this.formData.id = value.value[0].value;
      this.formData.houseArea = value.value[0].houseArea;
      this.showRoomPopup = false;
    },
    onRoomCancel() {
      this.showRoomPopup = false;
    },
  },
};
</script>

<style scoped>
.user-info {}

.user-info-container {
  display: flex;
  align-items: center;
  padding: 20rpx;
}

.user-avatar {
  border-radius: 50%;
  width: 100rpx;
  height: 100rpx;
}

.user-nickname {
  margin-left: 10px;
  font-size: 16px;
  color: #333;
}

.form-container {
  width: calc(100% - 40rpx);
  margin: 0 auto;
  margin-top: 20px;
  background-color: #fff;
  border-radius: 20rpx;
}

.field-container {
  padding: 14rpx 20rpx;
  border-bottom: 1px solid #ddd;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.label {
  min-width: 150rpx;
  font-size: 14px;
  color: #888;
}

.input {
  width: 100%;
  padding: 10rpx;
  font-size: 14px;
}

.submit-container {
  position: fixed;
  bottom: 0;
  width: 100%;
  padding: 40rpx 0;
  padding-bottom: 40rpx;
  background-color: #f5f5f5;
  box-shadow: 0 -10rpx 10rpx rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
}

.submit-btn {
  width: calc(100% - 20rpx) !important;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 90rpx;
  background: linear-gradient(90deg, #ff5e0b 0%, #ff7c02 100%);
  border-radius: 50rpx;
  font-weight: 600;
  font-size: 32rpx;
  color: #ffffff;
}

.dwdawwadf {
  width: calc(100% - 200rpx);
  position: absolute;
  bottom: -130px;
  height: 100px;
  border-radius: 10px;
  background-color: #fff;
  box-shadow: 0px 4px 8px rgba(255, 255, 255, 0.5);
  left: 150rpx;
  z-index: 1999;
  padding: 10px;
  color: #fff;
  overflow: auto;
  border: 1px solid rgba(0, 0, 0, 0.1);

}
</style>
